package com.qf.java2102.qihaonan.hotel.controller.cart;


import com.alibaba.fastjson.JSON;
import com.qf.java2102.qihaonan.hotel.entity.CartItem;
import com.qf.java2102.qihaonan.hotel.entity.ResultVO;
import com.qf.java2102.qihaonan.hotel.pojo.User;
import com.qf.java2102.qihaonan.hotel.service.ICartService;
import com.qf.java2102.qihaonan.hotel.service.impl.CartServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.Map;

/**
 * @author qhn
 * @version 1.0
 */
@WebServlet("/cart/delete")
public class CartDeleteController extends HttpServlet {

    private ICartService cartService = new CartServiceImpl();

    @Override
    public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        HttpSession session = request.getSession();

        //1.获取要删除菜品对应的cartItem
        String foodIdStr = request.getParameter("foodId");

        //2.获取当前登录用户对应的餐车
        User frontUser = (User) session.getAttribute("frontUser");
        Map<Long, CartItem> cart = (Map<Long, CartItem>) session.getAttribute(frontUser.getUserId()+"");
        //删除餐车中数据
        cart.remove(Long.valueOf(foodIdStr));

        //重新计算价格
        ResultVO<Map<String, Object>> resultVO = cartService.getCart(cart, frontUser);
        if(resultVO.getSuccess()) {
            //传数据
            response.getWriter().write(JSON.toJSONString(resultVO));
        } else {
            response.getWriter().write(JSON.toJSONString(ResultVO.error("删除失败")));
        }

    }

    @Override
    public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doPost(request, response);
    }
}
